<template>
  <el-main class="bg table_wrap comtabel_t">
    <el-form label-position="right" :model="query" class="form p_4" label-width="120">
      <el-row class="rows row1">


        <el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
          <el-form-item label="民宿名称">
            <el-input v-model="query.name_of_homestay"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
          <el-form-item label="用户姓名">
            <el-input v-model="query.user_name"></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="8" class="el_form_search_wrap">
          <el-form-item label="支付状态">
            <el-select v-model="query.pay_state">
              <el-option value="">全部</el-option>
              <el-option value="未支付">未支付</el-option>
              <el-option value="已支付">已支付</el-option>
            </el-select>
          </el-form-item>
        </el-col>

      </el-row>
      <el-row class="rows row2">

        <el-col :xs="24" :sm="24" :lg="24" class="search_btn_wrap search_btns">

          <el-col :xs="24" :sm="10" :lg="8" class="search_btn_1 search_btn_wrap_1 btns">

            <el-button type="primary" @click="search()" class="search_btn_find">查询</el-button>
            <el-button @click="reset()" style="margin-right: 74px;" class="search_btn_reset">重置</el-button>


            <el-button
                v-if="$check_action('/homestay_orders/table','del') || $check_action('/homestay_orders/view','del')"
                class="search_btn_del" type="danger" @click="delInfo()">删除
            </el-button>

          </el-col>
        </el-col>
      </el-row>

    </el-form>
    <el-table :data="list" @selection-change="selectionChange" @sort-change="$sortChange" style="width: 100%"
              id="dataTable">
      <el-table-column fixed type="selection" tooltip-effect="dark" width="55">
      </el-table-column>
      <el-table-column prop="merchant_users" @sort-change="$sortChange" label="商家用户"
                       v-if="$check_field('get','merchant_users')">
        <template slot-scope="scope">
          {{ get_user_merchant_users(scope.row['merchant_users']) }}
        </template>
      </el-table-column>
      <el-table-column prop="name_of_homestay" @sort-change="$sortChange" label="民宿名称"
                       v-if="$check_field('get','name_of_homestay')"/>
      <el-table-column prop="types_of_homestays" @sort-change="$sortChange" label="民宿类型"
                       v-if="$check_field('get','types_of_homestays')"/>
      <el-table-column prop="homestay_deposit" @sort-change="$sortChange" label="民宿押金"
                       v-if="$check_field('get','homestay_deposit')"/>
      <el-table-column prop="homestay_deposit_state" @sort-change="$sortChange" label="民宿押金状态"
                       v-if="$check_field('get','homestay_deposit')"/>
      <el-table-column prop="daily_price_of_homestay" @sort-change="$sortChange" label="民宿日价"
                       v-if="$check_field('get','daily_price_of_homestay')"/>
      <el-table-column prop="ordinary_users" @sort-change="$sortChange" label="用户昵称"
                       v-if="$check_field('get','ordinary_users')">
        <template slot-scope="scope">
          {{ get_user_ordinary_users(scope.row['ordinary_users']) }}
        </template>
      </el-table-column>
      <el-table-column prop="user_name" @sort-change="$sortChange" label="用户姓名"
                       v-if="$check_field('get','user_name')"/>
      <el-table-column prop="time_of_appointment" @sort-change="$sortChange" label="预约时间"
                       v-if="$check_field('get','time_of_appointment')">
        <template slot-scope="scope">
          {{ $toTime(scope.row["time_of_appointment"], "yyyy-MM-dd") }}
        </template>
      </el-table-column>
      <el-table-column prop="appointment_days" @sort-change="$sortChange" label="预约天数"
                       v-if="$check_field('get','appointment_days')"/>
      <el-table-column prop="total_cost" @sort-change="$sortChange" label="费用总计"
                       v-if="$check_field('get','total_cost')"/>
      <el-table-column label="支付状态" prop="pay_state"/>
      <el-table-column label="押金扣除" prop="deposit_deduction"/>
      <el-table-column label="备注" prop="remark"/>

      <el-table-column sortable prop="checkintime" label="入住时间">
        <template slot-scope="scope">
          {{ $toTime(scope.row["checkintime"], "yyyy-MM-dd hh:mm:ss") }}
        </template>
      </el-table-column>

      <el-table-column sortable prop="checkouttime" label="退住时间">
        <template slot-scope="scope">
          {{ $toTime(scope.row["checkouttime"], "yyyy-MM-dd hh:mm:ss") }}
        </template>
      </el-table-column>

      <el-table-column sortable prop="create_time" label="创建时间">
        <template slot-scope="scope">
          {{ $toTime(scope.row["create_time"], "yyyy-MM-dd hh:mm:ss") }}
        </template>
      </el-table-column>

      <el-table-column sortable prop="update_time" label="更新时间">
        <template slot-scope="scope">
          {{ $toTime(scope.row["update_time"], "yyyy-MM-dd hh:mm:ss") }}
        </template>
      </el-table-column>


      <el-table-column fixed="right" label="操作" v-if="$check_action('/homestay_orders/table','set') || $check_action('/homestay_orders/view','set') || $check_action('/homestay_orders/view','get')
						|| $check_action('/cancellation_of_order/table','add') || $check_action('/cancellation_of_order/view','add')
						|| $check_action('/renewal_order/table','add') || $check_action('/renewal_order/view','add')
						|| $check_action('/user_evaluate/table','add') || $check_action('/user_evaluate/view','add')
						">


        <template slot-scope="scope">
          <div class="view_a">
            <router-link class="e-button el-button--small is-plain el-button--success" style="margin: 5px !important;"
                         v-if="$check_action('/homestay_orders/table','set') || $check_action('/homestay_orders/view','set') || $check_action('/homestay_orders/view','get')"
                         :to="'./view?' + field + '=' + scope.row[field]"
                         size="small">
              <span>详情</span>
            </router-link>
            <!--跨表按钮-->
            <el-button class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" @click="to_table(scope.row,'/cancellation_of_order/view')"
                       v-if="($check_action('/cancellation_of_order/table','add') || $check_action('/cancellation_of_order/view','add')) && !scope.row['cancellation_of_order_limit']">
              <span>取消订单</span>
            </el-button>
            <el-button class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" @click="to_table(scope.row,'/renewal_order/view')"
                       v-if="($check_action('/renewal_order/table','add') || $check_action('/renewal_order/view','add')) && !scope.row['renewal_order_limit']">
              <span>续房</span>
            </el-button>
            <el-button class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" @click="to_table(scope.row,'/user_evaluate/view')"
                       v-if="($check_action('/user_evaluate/table','add') || $check_action('/user_evaluate/view','add')) && !scope.row['user_evaluate_limit']">
              <span>评价</span>
            </el-button>

            <el-button class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" @click="openPayModal(scope.row,'1')" v-if="scope.row.pay_state==='已支付'">
              <span>入住</span>
            </el-button>
            <el-button class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" @click="openPayModal(scope.row,'2')" v-if="scope.row.pay_state==='已入住'">
              <span>退住</span>
            </el-button>
            <el-button class="e-button el-button--small is-plain el-button--primary" style="margin: 5px !important;"
                       size="small" @click="openPayModal(scope.row,'3')"
                       v-if="scope.row.pay_state==='已查房' && scope.row.homestay_deposit_state==='已支付'">
              <span>退还押金</span>
            </el-button>
          </div>
        </template>
      </el-table-column>

    </el-table>

    <!-- 分页器 -->
    <div class="mt text_center">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="query.page" :page-sizes="[7, 10, 30, 100]" :page-size="query.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="count">
      </el-pagination>
    </div>
    <!-- /分页器 -->

    <div class="modal_wrap" v-if="showModal">
      <div class="modal_box">
        <p class="modal_box_title">重要提醒</p>
        <p class="modal_box_text">当前有数据达到预警值！</p>
        <p class="modal_box_text">{{ message }}</p>
        <div class="btn_box">
          <span @click="closeModal">取消</span>
          <span @click="closeModal">确定</span>
        </div>
      </div>
    </div>

    <!-- 新增：退还押金弹窗 -->
    <el-dialog title="退还押金" :visible.sync="depositDialogVisible" width="30%">
      <el-form label-width="100px">
        <el-form-item label="押金扣除">
          <el-input v-model="depositDeduction" placeholder="请输入押金扣除数"></el-input>
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="depositRemark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="depositDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDepositReturn">确认</el-button>
      </span>
    </el-dialog>

  </el-main>
</template>
<script>
import mixin from "@/mixins/page.js";

export default {
  mixins: [mixin],
  data() {
    return {
      // 弹框
      showModal: false,
      // 获取数据地址
      url_get_list: "~/api/homestay_orders/get_list?like=0",
      url_del: "~/api/homestay_orders/del?",
      // 字段ID
      field: "homestay_orders_id",

      // 查询
      query: {
        "size": 7,
        "page": 1,
        "name_of_homestay": "",
        "user_name": "",
        "pay_state": "",
        "login_time": "",
        "create_time": "",
        "orderby": `create_time desc`
      },
      homeclearObj: {
        "business_user": 0, // 商家用户
        "name_of_homestay": '', // 民宿名称
        "location_of_homestay": '', // 民宿位置
        "cleaning_the_user": 0, // 打扫用户

        "cleaning_time": new Date(), // 打扫时间
        "cleaning_remarks": '系统分配', // 打扫备注
        "room_cleaning_id": 0, // ID
        "img": '',
        "state": "待打扫"
      },
      // 数据
      list: [],
      pay_obj: {
        id: "",
        itemId: ""
      },
      pay_qrcode: "",
      // 用户列表
      list_user_merchant_users: [],
      // 用户列表
      list_user_ordinary_users: [],
      message: '',

      // 新增：退还押金弹窗相关数据
      depositDialogVisible: false, // 退还押金弹窗可见性
      depositDeduction: '', // 押金扣除
      depositRemark: '', // 备注内容
      currentRow: null, // 当前操作的行数据
    }
  },
  methods: {
    // 关闭弹框
    closeModal() {
      this.showModal = false;
    },
    /**
     * @description 获取到列表事件
     * @param {Object} res 响应结果
     */
    get_list_after: function get_list_after(res, func, url) {
      let _this = this
      _this.list.map((item) => {
        let param = {
          source_table: "homestay_orders",
          source_user_id: _this.user.user_id
        };
        if (item.cancellation_of_order_limit_times > 0) {
          _this.$get("~/api/cancellation_of_order/count?", param, (result) => {
            if (result) {
              if (result.result >= item.cancellation_of_order_limit_times) {
                _this.$set(item, 'cancellation_of_order_limit', true);
              } else {
                _this.$set(item, 'cancellation_of_order_limit', false);
              }
            }
          })
        } else {
          _this.$set(item, 'cancellation_of_order_limit', false);
        }
        Object.assign(item, param)
      })
      _this.list.map((item) => {
        let param = {
          source_table: "homestay_orders",
          source_user_id: _this.user.user_id
        };
        if (item.renewal_order_limit_times > 0) {
          _this.$get("~/api/renewal_order/count?", param, (result) => {
            if (result) {
              if (result.result >= item.renewal_order_limit_times) {
                _this.$set(item, 'renewal_order_limit', true);
              } else {
                _this.$set(item, 'renewal_order_limit', false);
              }
            }
          })
        } else {
          _this.$set(item, 'renewal_order_limit', false);
        }
        Object.assign(item, param)
      })
      _this.list.map((item) => {
        let param = {
          source_table: "homestay_orders",
          source_user_id: _this.user.user_id
        };
        if (item.user_evaluate_limit_times > 0) {
          _this.$get("~/api/user_evaluate/count?", param, (result) => {
            if (result) {
              if (result.result >= item.user_evaluate_limit_times) {
                _this.$set(item, 'user_evaluate_limit', true);
              } else {
                _this.$set(item, 'user_evaluate_limit', false);
              }
            }
          })
        } else {
          _this.$set(item, 'user_evaluate_limit', false);
        }
        Object.assign(item, param)
      })
    },
    get_list_before(param) {
      var user_group = this.user.user_group;
      if (user_group != "管理员") {
        let sqlwhere = "(";
        if (user_group == "商家用户") {
          sqlwhere += "merchant_users = " + this.user.user_id + " or ";
        }
        if (user_group == "普通用户") {
          sqlwhere += "ordinary_users = " + this.user.user_id + " or ";
        }
        if (sqlwhere.length > 1) {
          sqlwhere = sqlwhere.substr(0, sqlwhere.length - 4);
          sqlwhere += ")";
          param["sqlwhere"] = sqlwhere;
        }
      }
      return param;
    },
    /**
     * 获取商家用户用户列表
     */
    async get_list_user_merchant_users() {
      var json = await this.$get("~/api/user/get_list?user_group=商家用户");
      if (json.result && json.result.list) {
        this.list_user_merchant_users = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    },

    get_user_merchant_users(id) {
      var obj = this.list_user_merchant_users.getObj({"user_id": id});
      var ret = "";
      if (obj) {
        ret = obj.nickname + "-" + obj.username;
      }
      return ret;
    },
    /**
     * 获取普通用户用户列表
     */
    async get_list_user_ordinary_users() {
      var json = await this.$get("~/api/user/get_list?user_group=普通用户");
      if (json.result && json.result.list) {
        this.list_user_ordinary_users = json.result.list;
      } else if (json.error) {
        console.error(json.error);
      }
    },

    get_user_ordinary_users(id) {
      var obj = this.list_user_ordinary_users.getObj({"user_id": id});
      var ret = "";
      if (obj) {
        ret = obj.nickname;
      }
      return ret;
    },
    openPayModal(v, type) {
      this.pay_obj.id = v.homestay_orders_id
      this.pay_obj.itemId = v.source_id
      this.pay_obj.source_user_id = v.source_user_id;

      // 修改：如果是退还押金操作，显示弹窗
      if (type === '3') {
        this.showDepositDialog(v);
      } else {
        this.submitPay(type)
      }
    },

    // 新增：显示退还押金弹窗
    showDepositDialog(row) {
      this.currentRow = row;
      this.depositDeduction = ''; // 默认不扣除
      this.depositRemark = ''; // 清空备注内容
      this.depositDialogVisible = true;
    },

    // 新增：确认退还押金
    confirmDepositReturn() {
      if (!this.depositRemark.trim()) {
        this.$toast('备注信息不能为空！', 'warning');
        return;
      }
      this.depositDialogVisible = false;
      // 更新押金状态和备注
      this.updateDepositStatus();
    },

    // 新增：更新押金状态和备注
    updateDepositStatus() {
      let _this = this;
      let param = {
        "homestay_deposit_state": "已退还",
        "deposit_deduction": this.depositDeduction,
        "remark": this.depositRemark
      };

      let url = this.$toUrl(this.query, "~/api/homestay_orders/set?homestay_orders_id=" + this.pay_obj.id);
      this.$post(url, param, function (json, status) {
        console.log("提交结果：", json);
        if (json.result) {
          _this.$toast('押金退还成功！', 'success');
          _this.get_list();
          // 上架房价
          _this.setOnSale(_this.pay_obj.itemId);
        } else if (json.error) {
          _this.$toast(json.error.message, 'danger');
        }
      });
    },

    setOnSale(id) {
      let _this = this;
      let url = this.$toUrl(this.query, "~/api/homestay_information/set?homestay_information_id=" + id);
      let param = {"on_sale": "1"};
      this.$post(url, param, function (json, status) {
        if (json.result) {
          _this.$toast('房价已上架', 'success');
        } else if (json.error) {
          _this.$toast(json.error.message, 'danger');
        }
      });
    },

    submitPay(type) {
      let param;
      if (type === '1') {//入住
        param = {"pay_state": "已入住", "checkintime": new Date()};
      } else if (type === '2') {//退住
        param = {"pay_state": "已退住", "checkouttime": new Date()};
      } else {//退押金 - 这部分逻辑已移至 updateDepositStatus 方法
        return;
      }

      // ... existing code ...
    },

    async getEmpUserId(merchantUserId) {
      var json = await this.$get("~/api/employee_user/getRandomUserId?merchantUserId=" + merchantUserId);
      if (json) {
        this.homeclearObj.cleaning_the_user = json;
      } else {
        this.homeclearObj.cleaning_the_user = null;
      }
    },

    async addHomeClear(id, merchantUserId) {
      let _this = this;
      _this.getEmpUserId(merchantUserId);
      var json = await this.$get("~/api/homestay_information/get_obj?homestay_information_id=" + id);
      if (json.result && json.result.obj) {
        var obj = json.result.obj;
        this.homeclearObj.business_user = obj.merchant_users;
        //民宿位置
        this.homeclearObj.location_of_homestay = obj.location_of_homestay;
        //名字
        this.homeclearObj.name_of_homestay = obj.name_of_homestay;
        this.homeclearObj.homestay_orders_id = this.pay_obj.id

        let url = this.$toUrl(this.homeclearObj, "~/api/room_cleaning/add?");
        this.$post(url, this.homeclearObj, function (json, status) {
          console.log("提交结果：", json);
          if (json.result) {
            _this.$toast('操作成功！', 'success');
            _this.get_list();
            if (type === '3') { //上架房价
              _this.setOnSale(_this.pay_obj.itemId)
            } else if (type === '2') {//推送打扫房间还能

            }
          } else if (json.error) {
            _this.$toast(json.error.message, 'danger');
          }
        });

      } else if (json.error) {
        console.error(json.error);
      }
    },
  },
  created() {
    this.get_list_user_merchant_users();
    this.get_list_user_ordinary_users();
  }
}
</script>

<style type="text/css">
.bg {
  background: white;
}

.form.p_4 {
  padding: 1rem;
}

.form .el-input {
  width: initial;
}

.mt {
  margin-top: 1rem;
}

.text_center {
  text-align: center;
}

.float-right {
  float: right;
}


.modal_wrap {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 9999999999;
}

.modal_wrap .modal_box {
  width: 400px;
  height: auto;
  background: url("../../assets/modal_bg.jpg") no-repeat center;
  background-size: cover;
  position: absolute;
  top: 50%;
  left: 50%;
  margin-left: -200px;
  margin-top: -100px;
  border-radius: 10px;
  padding: 10px;
}

.modal_wrap .modal_box .modal_box_close {
  font-size: 20px;
  position: absolute;
  top: 10px;
  right: 10px;
  cursor: pointer;
}

.modal_wrap .modal_box .modal_box_title {
  text-align: center;
  font-size: 18px;
  margin: 16px auto;
  color: #fff;
  border-bottom: 1px solid rgba(117, 116, 116, 0.5);
  padding-bottom: 16px;
  width: 356px;
}

.modal_wrap .modal_box .modal_box_text {
  text-align: center;
  font-size: 14px;
  color: #fff;
  margin: 5px auto;
  width: 90%;
}

.modal_wrap .modal_box .btn_box {
  display: flex;
  flex-direction: row;
  justify-content: center;
  margin-top: 42px;
  margin-bottom: 20px;
}

.modal_wrap .modal_box .btn_box span {
  display: inline-block;
  width: 80px;
  height: 30px;
  line-height: 30px;
  text-align: center;
  border: 1px solid #ccc;
  font-size: 14px;
  cursor: pointer;
  color: #fff;
}

.modal_wrap .modal_box .btn_box span:nth-child(2) {
  background: #409EFF;
  color: #fff;
  border-color: #409EFF;
  margin-left: 15px;
}

.el-date-editor .el-range-separator {
  width: 10% !important;
}
</style>
